package com.fly.lambda.controller;

import com.fly.lambda.framework.web.session.AccountSession;
import com.fly.lambda.framework.web.session.support.SessionInfo;
import com.fly.lambda.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Fly on 2016/7/13.
 */
@Controller
@RequestMapping("/manage")
public class ManageCtrl {

    @Autowired
    LoginService loginService;

    @RequestMapping("/index")
    public String manageIndex(
            @SessionInfo AccountSession session,
            ModelMap model
            ){
        model.addAttribute("loginName", session.getLoginName());
        return "/manage/index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String toLogin(
            @RequestParam(value = "redirUrl", required = false, defaultValue = "")String redirUrl,
            ModelMap model
    ){
        model.addAttribute("redir", redirUrl);
        return "manage/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> doLogin(
            @RequestParam(value = "loginName", required = false, defaultValue = "")String loginName,
            @RequestParam(value = "password", required = false, defaultValue = "")String password,
            HttpServletResponse response
    ){
        Map<String, String> map = new HashMap<String, String>();
        if (loginService.login(response, loginName, password)){
            map.put("result", "success");
            map.put("msg", "登录成功");
        }
        else {
            map.put("result", "error");
            map.put("msg", "用户名或密码错误");
        }
        return map;
    }

    @RequestMapping("/logout")
    public String logout(
            HttpServletResponse response,
            HttpServletRequest request
    ){
        loginService.logout(response, request);
        return "redirect:/manage/index";
    }
}
